const Shop = require('../models/shop.model');
const Product = require('../models/product.model');
const User = require('../models/user.model');
const ShopApprovalHistory = require('../models/ShopApprovalHistory');
const mongoose = require('mongoose');

/**
 * 获取商店列表 (管理员)
 * GET /api/admin/shops
 */
exports.getShops = async (req, res, next) => {
  try {
    const {
      keyword = '',
      status = '',
      type = '',
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 构建查询条件
    const query = {};

    // 关键词搜索
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } },
        { categoriesText: { $regex: keyword, $options: 'i' } }
      ];
    }

    // 状态筛选
    if (status) {
      query.status = status;
    }

    // 类型筛选
    if (type) {
      query.type = type;
    }

    // 获取总数
    const total = await Shop.countDocuments(query);

    // 获取商店列表
    const shops = await Shop.find(query)
      .populate('owner', 'name email avatar')
      .sort(sort)
      .skip(skip)
      .limit(limitNumber);

    // 格式化数据，添加统计信息
    const formattedShops = await Promise.all(
      shops.map(async (shop) => {
        const productCount = await Product.countDocuments({ shop: shop._id });

        return {
          _id: shop._id,
          name: shop.name,
          description: shop.description,
          logo: shop.logo,
          banner: shop.banner,
          owner: shop.owner,
          status: shop.status,
          type: shop.type,
          categories: shop.categories,
          rating: shop.rating?.overall || 0,
          reviewCount: shop.reviewCount,
          certification: shop.certification,
          stats: {
            ...shop.stats,
            totalProducts: productCount
          },
          createdAt: shop.createdAt,
          updatedAt: shop.updatedAt
        };
      })
    );

    res.json({
      data: formattedShops,
      total,
      page: pageNumber,
      limit: limitNumber,
      totalPages: Math.ceil(total / limitNumber)
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取商店详情 (管理员)
 * GET /api/admin/shops/:id
 */
exports.getShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const shop = await Shop.findById(shopId)
      .populate('owner', 'name email avatar phone createdAt');

    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    // 获取商店统计数据
    const productCount = await Product.countDocuments({ shop: shopId });
    const products = await Product.find({ shop: shopId })
      .select('name price countInStock rating salesCount')
      .sort('-salesCount')
      .limit(5);

    // 构建详细信息
    const shopDetails = {
      ...shop.toObject(),
      stats: {
        ...shop.stats,
        totalProducts: productCount
      },
      topProducts: products
    };

    res.json({
      success: true,
      data: shopDetails
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 创建商店 (管理员)
 * POST /api/admin/shops
 */
exports.createShop = async (req, res, next) => {
  try {
    const {
      name,
      description,
      logo,
      banner,
      ownerId,
      categories,
      type = 'personal',
      status = 'pending',
      contact,
      announcement,
      tags,
      shipping,
      afterSales
    } = req.body;

    // 验证店主用户是否存在
    const owner = await User.findById(ownerId);
    if (!owner) {
      return res.status(400).json({
        success: false,
        message: '指定的店主用户不存在'
      });
    }

    // 检查用户是否已有店铺
    const existingShop = await Shop.findOne({ owner: ownerId });
    if (existingShop) {
      return res.status(400).json({
        success: false,
        message: '该用户已经拥有一个店铺'
      });
    }

    // 创建商店
    const shop = await Shop.create({
      name,
      description,
      logo,
      banner,
      owner: ownerId,
      categories: categories || [],
      type,
      status,
      contact,
      announcement,
      tags,
      shipping,
      afterSales
    });

    // 填充店主信息
    await shop.populate('owner', 'name email avatar');

    res.status(201).json({
      success: true,
      data: shop,
      message: '商店创建成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新商店 (管理员)
 * PUT /api/admin/shops/:id
 */
exports.updateShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const updateData = { ...req.body };

    const shop = await Shop.findByIdAndUpdate(
      shopId,
      updateData,
      { new: true, runValidators: true }
    ).populate('owner', 'name email avatar');

    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    res.json({
      success: true,
      data: shop,
      message: '商店更新成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除商店 (管理员)
 * DELETE /api/admin/shops/:id
 */
exports.deleteShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    // 检查商店是否有商品
    const productCount = await Product.countDocuments({ shop: shopId });
    if (productCount > 0) {
      return res.status(400).json({
        success: false,
        message: '无法删除有商品的商店，请先删除所有商品'
      });
    }

    const shop = await Shop.findByIdAndDelete(shopId);

    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    res.json({
      success: true,
      message: '商店删除成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 审核商店 (管理员)
 * POST /api/admin/shops/:id/approve
 */
exports.approveShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;
    const { status, reason } = req.body;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    if (!['approved', 'rejected'].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的审核状态'
      });
    }

    // 获取原商店信息
    const originalShop = await Shop.findById(shopId);
    if (!originalShop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    const previousStatus = originalShop.status;
    const newStatus = status === 'approved' ? 'active' : 'rejected';

    const updateData = {
      status: newStatus
    };

    if (status === 'rejected' && reason) {
      updateData.rejectionReason = reason;
    }

    if (status === 'approved') {
      updateData['certification.isVerified'] = true;
      updateData['certification.verifiedAt'] = new Date();
    }

    const shop = await Shop.findByIdAndUpdate(
      shopId,
      updateData,
      { new: true, runValidators: true }
    ).populate('owner', 'name email avatar');

    // 记录审核历史
    try {
      await ShopApprovalHistory.recordApproval({
        shopId: shop._id,
        shopName: shop.name,
        action: status,
        reason: reason || '',
        operatorId: req.admin._id,
        operatorName: req.admin.name,
        previousStatus,
        newStatus,
        metadata: {
          adminId: req.admin._id,
          adminName: req.admin.name,
          timestamp: new Date()
        }
      });
    } catch (historyError) {
      console.error('记录审核历史失败:', historyError);
      // 不影响主流程，只记录错误
    }

    res.json({
      success: true,
      data: shop,
      message: `商店${status === 'approved' ? '审核通过' : '审核拒绝'}`
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 暂停/恢复商店 (管理员)
 * POST /api/admin/shops/:id/suspend
 * POST /api/admin/shops/:id/resume
 */
exports.suspendShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;
    const { reason } = req.body;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const shop = await Shop.findByIdAndUpdate(
      shopId,
      {
        status: 'suspended',
        suspensionReason: reason || '违规操作'
      },
      { new: true, runValidators: true }
    ).populate('owner', 'name email avatar');

    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    res.json({
      success: true,
      data: shop,
      message: '商店已暂停'
    });
  } catch (error) {
    next(error);
  }
};

exports.resumeShop = async (req, res, next) => {
  try {
    const shopId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const shop = await Shop.findByIdAndUpdate(
      shopId,
      {
        status: 'active',
        $unset: { suspensionReason: 1 }
      },
      { new: true, runValidators: true }
    ).populate('owner', 'name email avatar');

    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    res.json({
      success: true,
      data: shop,
      message: '商店已恢复'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取待审核商店列表 (管理员)
 * GET /api/admin/shops/pending
 */
exports.getPendingShops = async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 查询待审核商店
    const query = { status: 'pending' };

    const total = await Shop.countDocuments(query);

    const shops = await Shop.find(query)
      .populate('owner', 'name email avatar phone')
      .sort(sort)
      .skip(skip)
      .limit(limitNumber);

    res.json({
      data: shops,
      total,
      page: pageNumber,
      limit: limitNumber,
      totalPages: Math.ceil(total / limitNumber)
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取商店统计信息 (管理员)
 * GET /api/admin/shops/:id/stats
 */
exports.getShopStats = async (req, res, next) => {
  try {
    const shopId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const shop = await Shop.findById(shopId);
    if (!shop) {
      return res.status(404).json({
        success: false,
        message: '商店不存在'
      });
    }

    // 获取商品统计
    const productStats = await Product.aggregate([
      { $match: { shop: new mongoose.Types.ObjectId(shopId) } },
      {
        $group: {
          _id: null,
          totalProducts: { $sum: 1 },
          totalStock: { $sum: '$countInStock' },
          averagePrice: { $avg: '$price' },
          totalSales: { $sum: '$salesCount' },
          averageRating: { $avg: '$rating' }
        }
      }
    ]);

    // 获取分类统计
    const categoryStats = await Product.aggregate([
      { $match: { shop: new mongoose.Types.ObjectId(shopId) } },
      {
        $group: {
          _id: '$category',
          count: { $sum: 1 },
          totalSales: { $sum: '$salesCount' }
        }
      },
      { $sort: { count: -1 } }
    ]);

    const stats = {
      products: productStats[0] || {
        totalProducts: 0,
        totalStock: 0,
        averagePrice: 0,
        totalSales: 0,
        averageRating: 0
      },
      categories: categoryStats,
      shop: {
        followers: shop.followers ? shop.followers.length : 0,
        rating: shop.rating?.overall || 0,
        reviewCount: shop.reviewCount,
        createdAt: shop.createdAt
      }
    };

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 批量操作商店 (管理员)
 * POST /api/admin/shops/batch-action
 */
exports.batchActionShops = async (req, res, next) => {
  try {
    const { ids, action, data } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的商店ID列表'
      });
    }

    let updateData = {};
    let message = '';
    let isDelete = false;

    switch (action) {
      case 'approve':
        updateData = {
          status: 'active',
          'certification.isVerified': true,
          'certification.verifiedAt': new Date()
        };
        message = '批量审核通过';
        break;
      case 'reject':
        updateData = {
          status: 'rejected',
          rejectionReason: data?.reason || '不符合要求'
        };
        message = '批量审核拒绝';
        break;
      case 'suspend':
        updateData = {
          status: 'suspended',
          suspensionReason: data?.reason || '违规操作'
        };
        message = '批量暂停';
        break;
      case 'resume':
        updateData = {
          status: 'active',
          $unset: { suspensionReason: 1 }
        };
        message = '批量恢复';
        break;
      case 'delete':
        isDelete = true;
        message = '批量删除';
        break;
      default:
        return res.status(400).json({
          success: false,
          message: '无效的操作类型'
        });
    }

    let result;
    if (isDelete) {
      // 检查是否有商店包含商品
      const shopsWithProducts = await Product.find({ shop: { $in: ids } }).distinct('shop');
      if (shopsWithProducts.length > 0) {
        return res.status(400).json({
          success: false,
          message: `有 ${shopsWithProducts.length} 个商店包含商品，无法删除。请先删除商品。`
        });
      }

      result = await Shop.deleteMany({ _id: { $in: ids } });

      res.json({
        success: true,
        message: `${message}成功，删除了 ${result.deletedCount} 个商店`
      });
    } else {
      result = await Shop.updateMany(
        { _id: { $in: ids } },
        updateData
      );

      res.json({
        success: true,
        message: `${message}成功，影响 ${result.modifiedCount} 个商店`
      });
    }
  } catch (error) {
    next(error);
  }
};

/**
 * 获取商店商品列表 (管理员)
 * GET /api/admin/shops/:id/products
 */
exports.getShopProducts = async (req, res, next) => {
  try {
    const shopId = req.params.id;
    const {
      page = 1,
      limit = 10,
      keyword = '',
      category = '',
      status = ''
    } = req.query;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 构建查询条件
    const query = { shop: shopId };

    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } },
        { brand: { $regex: keyword, $options: 'i' } }
      ];
    }

    if (category) {
      query.category = category;
    }

    if (status) {
      query.status = status;
    }

    const total = await Product.countDocuments(query);

    const products = await Product.find(query)
      .populate('shop', 'name logo')
      .sort('-createdAt')
      .skip(skip)
      .limit(limitNumber);

    res.json({
      data: products,
      total,
      page: pageNumber,
      limit: limitNumber,
      totalPages: Math.ceil(total / limitNumber)
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取审核历史 (管理员)
 * GET /api/admin/shops/approval-history
 */
exports.getApprovalHistory = async (req, res, next) => {
  try {
    const {
      page = 1,
      limit = 10,
      keyword,
      action,
      startDate,
      endDate,
      operatorId
    } = req.query;

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      keyword,
      action,
      startDate,
      endDate,
      operatorId
    };

    const result = await ShopApprovalHistory.getAllHistory(options);

    // 格式化返回数据
    const formattedData = result.data.map(record => ({
      id: record._id,
      shopId: record.shop?._id || record.shop,
      shopName: record.shopName,
      action: record.action,
      reason: record.reason,
      operator: record.operatorName,
      operatorId: record.operator,
      createdAt: record.createdAt,
      previousStatus: record.previousStatus,
      newStatus: record.newStatus
    }));

    res.json({
      success: true,
      data: formattedData,
      pagination: result.pagination,
      total: result.total
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取商店审核历史 (管理员)
 * GET /api/admin/shops/:id/approval-history
 */
exports.getShopApprovalHistory = async (req, res, next) => {
  try {
    const shopId = req.params.id;
    const {
      page = 1,
      limit = 10,
      action,
      startDate,
      endDate
    } = req.query;

    if (!mongoose.Types.ObjectId.isValid(shopId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商店ID'
      });
    }

    const options = {
      page: parseInt(page),
      limit: parseInt(limit),
      action,
      startDate,
      endDate
    };

    const result = await ShopApprovalHistory.getShopHistory(shopId, options);

    // 格式化返回数据
    const formattedData = result.data.map(record => ({
      id: record._id,
      shopId: record.shop?._id || record.shop,
      shopName: record.shopName,
      action: record.action,
      reason: record.reason,
      operator: record.operatorName,
      operatorId: record.operator,
      createdAt: record.createdAt,
      previousStatus: record.previousStatus,
      newStatus: record.newStatus
    }));

    res.json({
      success: true,
      data: formattedData,
      pagination: result.pagination,
      total: result.total
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取审核统计 (管理员)
 * GET /api/admin/shops/approval-stats
 */
exports.getApprovalStats = async (req, res, next) => {
  try {
    const {
      startDate,
      endDate,
      operatorId
    } = req.query;

    const options = {
      startDate,
      endDate,
      operatorId
    };

    const stats = await ShopApprovalHistory.getApprovalStats(options);

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取总体统计数据 (管理员)
 * GET /api/admin/shops/overall-stats
 */
exports.getOverallStats = async (req, res, next) => {
  try {
    const { startDate, endDate, shopId } = req.query;

    // 构建查询条件
    const dateQuery = {};
    if (startDate || endDate) {
      dateQuery.createdAt = {};
      if (startDate) dateQuery.createdAt.$gte = new Date(startDate);
      if (endDate) dateQuery.createdAt.$lte = new Date(endDate);
    }

    const shopQuery = shopId ? { _id: shopId } : {};

    // 并行查询各项统计数据
    const [
      totalShops,
      activeShops,
      // 这里需要Order模型来计算营收和订单数
      // 暂时使用模拟数据
    ] = await Promise.all([
      Shop.countDocuments({ ...shopQuery, ...dateQuery }),
      Shop.countDocuments({ ...shopQuery, ...dateQuery, status: 'active' }),
    ]);

    // 计算平均评分
    const ratingStats = await Shop.aggregate([
      { $match: { ...shopQuery, ...dateQuery } },
      {
        $group: {
          _id: null,
          averageRating: { $avg: '$rating.overall' },
          totalRating: { $sum: '$rating.overall' }
        }
      }
    ]);

    const averageRating = ratingStats.length > 0 ? ratingStats[0].averageRating || 0 : 0;

    // 模拟数据 - 实际应该从订单表计算
    const mockStats = {
      totalRevenue: 1250000,
      totalOrders: 8500,
      growthRate: 15.6
    };

    res.json({
      success: true,
      data: {
        totalShops,
        activeShops,
        totalRevenue: mockStats.totalRevenue,
        totalOrders: mockStats.totalOrders,
        averageRating: Number(averageRating.toFixed(1)),
        growthRate: mockStats.growthRate
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取商店排行榜 (管理员)
 * GET /api/admin/shops/rankings
 */
exports.getShopRankings = async (req, res, next) => {
  try {
    const { startDate, endDate, limit = 10 } = req.query;

    // 获取商店基本信息
    const shops = await Shop.find({ status: 'active' })
      .select('name logo rating')
      .limit(parseInt(limit));

    // 模拟排行数据 - 实际应该从订单表计算
    const rankings = shops.map((shop, index) => ({
      shopId: shop._id,
      shopName: shop.name,
      shopLogo: shop.logo,
      revenue: Math.floor(Math.random() * 500000) + 100000,
      orders: Math.floor(Math.random() * 1000) + 100,
      rating: shop.rating?.overall || 4.5,
      growth: (Math.random() - 0.5) * 50, // -25% 到 +25%
      rank: index + 1
    }));

    // 按营收排序
    rankings.sort((a, b) => b.revenue - a.revenue);
    rankings.forEach((item, index) => {
      item.rank = index + 1;
    });

    res.json({
      success: true,
      data: rankings
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取营收趋势 (管理员)
 * GET /api/admin/shops/revenue-trend
 */
exports.getRevenueTrend = async (req, res, next) => {
  try {
    const { startDate, endDate, shopId } = req.query;

    // 生成日期范围
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const end = endDate ? new Date(endDate) : new Date();

    const trendData = [];
    const current = new Date(start);

    while (current <= end) {
      trendData.push({
        date: current.toISOString().split('T')[0],
        revenue: Math.floor(Math.random() * 50000) + 10000,
        orders: Math.floor(Math.random() * 100) + 20
      });
      current.setDate(current.getDate() + 1);
    }

    res.json({
      success: true,
      data: trendData
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取分类统计 (管理员)
 * GET /api/admin/shops/category-stats
 */
exports.getCategoryStats = async (req, res, next) => {
  try {
    const { startDate, endDate, shopId } = req.query;

    // 从商店表获取分类统计
    const categoryStats = await Shop.aggregate([
      {
        $match: {
          status: 'active',
          ...(shopId ? { _id: mongoose.Types.ObjectId(shopId) } : {})
        }
      },
      { $unwind: '$categories' },
      {
        $group: {
          _id: '$categories',
          count: { $sum: 1 }
        }
      },
      {
        $project: {
          category: '$_id',
          count: 1,
          revenue: { $multiply: ['$count', { $add: [{ $multiply: [Math.random(), 100000] }, 50000] }] }
        }
      }
    ]);

    const formattedStats = categoryStats.map(stat => ({
      category: stat.category,
      count: stat.count,
      revenue: Math.floor(stat.revenue)
    }));

    res.json({
      success: true,
      data: formattedStats
    });
  } catch (error) {
    next(error);
  }
};

module.exports = exports;
